/*
 *   Copyright 2021 zzh
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

package com.aduib.boot.common.buffer;

import com.aduib.boot.common.util.ExceptionUtils;

import java.io.IOException;
import java.io.OutputStream;

/**
 * @description: BufferInputStream
 * @author: zzh
 * @date: 2021/12/13 15:51
 */
public class BufferedOutputStream extends OutputStream {

  private Buffer buf;

  private int capacity;

  private boolean isClosed = false;

  public BufferedOutputStream(int capacity) {
    this.capacity = capacity;
    this.buf = BufferUtils.allocateBuffer(capacity);
  }

  public BufferedOutputStream(Buffer buf) {
    this.buf = buf;
    this.capacity = buf.capacity();
  }

  private synchronized void grow() {
    if (buf.writableBytes() <= (capacity / 2)) {
      int newCapacity = capacity << 1;
      Buffer newBuffer = BufferUtils.allocateBuffer(newCapacity);
      BufferUtils.copy(buf, newBuffer);
      buf.deallocate();
      this.buf = newBuffer;
      this.capacity = newCapacity;
    }
  }

  @Override
  public void write(int i) throws IOException {
    ExceptionUtils.throwStreamAlreadyClosedException(isClosed);
    grow();
    this.buf.writeByte((byte) i);
  }

  @Override
  public void write(byte[] b) throws IOException {
    ExceptionUtils.throwStreamAlreadyClosedException(isClosed);
    grow();
    this.buf.write(b);
  }

  @Override
  public void write(byte[] b, int off, int len) throws IOException {
    ExceptionUtils.throwStreamAlreadyClosedException(isClosed);
    grow();
    this.buf.write(b, off, len);
  }

  @Override
  public void flush() throws IOException {}

  @Override
  public void close() throws IOException {
    BufferUtils.freeBuffer(buf);
    isClosed = true;
  }

  public Buffer getBuf() {
    return buf;
  }
}
